package com.dongdong.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdong.data.DataResult;
import com.dongdong.data.ResponseStatusEnum;
import com.dongdong.pojo.TbUser;
import com.dongdong.service.TbUserService;
import com.dongdong.shiro.ShiroUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Deacription TODO
 * @Author Lenovo
 * @Date 2020/12/19 15:18
 * @Version 1.0
 **/
@Controller
public class IndexController {

    private static final Logger logger = LoggerFactory.getLogger(IndexController.class);

    @Resource
    private RedisTemplate redisTemplate;

    @Reference
    private TbUserService tbUserService;

    @RequestMapping({"index","/"})
    public String index(){
        return "index";
    }

    @RequestMapping("toLogin")
    public String toLogin(){
        return "login";
    }

    @RequestMapping("toRegister")
    public String toRegister(){
        return "register";
    }

    @RequestMapping("login")
    public String login(String username, String password, Model model){
        UsernamePasswordToken token=new UsernamePasswordToken(username,password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
        }catch (UnknownAccountException u){
            model.addAttribute("message","用户不存在");
            return "login";
        }catch (IncorrectCredentialsException i){
            model.addAttribute("message","密码不正确");
            return "login";
        }
        return "redirect:/index";
    }

    @RequestMapping("register")
    @ResponseBody
    public DataResult register(TbUser tbUser,String code,String rePwd) {
        System.out.println(tbUser);
        System.out.println(code);
        try {
            if (StringUtils.isBlank(tbUser.getUsername())) {
                return DataResult.response(ResponseStatusEnum.INTERNAL_SERVER_ERROR).setData("用户名不能为空");
            }
            if (StringUtils.isBlank(tbUser.getPassword())) {
                return DataResult.response(ResponseStatusEnum.INTERNAL_SERVER_ERROR).setData("密码不能为空");
            }
            if (!rePwd.equals(tbUser.getPassword())) {
                return DataResult.response(ResponseStatusEnum.INTERNAL_SERVER_ERROR).setData("密码不一致");
            }
            if (StringUtils.isBlank(tbUser.getPhone())) {
                return DataResult.response(ResponseStatusEnum.INTERNAL_SERVER_ERROR).setData("手机号不能为空");
            }
            String codes = (String) redisTemplate.opsForHash().get("phoneCode:", tbUser.getPhone());
            if (!code.equals(codes)) {
                return DataResult.response(ResponseStatusEnum.INTERNAL_SERVER_ERROR).setData("验证码不一致");
            }
            String salt = ShiroUtils.generateSalt(6);
            String md5 = ShiroUtils.encryptPassword("MD5", tbUser.getPassword(), salt, 3);
            tbUser.setSalt(salt);
            tbUser.setPassword(md5);
            tbUser.setCreated(new Date());
            tbUser.setUpdated(new Date());

            //判断用户是否存在
            List<TbUser> users = tbUserService.getUserName(tbUser.getUsername());
            if (users.size() == 1) {
                return DataResult.response(ResponseStatusEnum.INTERNAL_SERVER_ERROR).setData("用户已存在");
            }
            int i = tbUserService.insertUser(tbUser);
            if (i > 0) {
                return DataResult.response(ResponseStatusEnum.SUCCESS);
            }else {
                return DataResult.response(ResponseStatusEnum.INTERNAL_SERVER_ERROR);
            }
        } catch (Exception e) {
            logger.error("增加失败");
            return DataResult.response(ResponseStatusEnum.INTERNAL_SERVER_ERROR);
        }
    }

}

